import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/shopping_car_list_entity.dart';
import 'package:taonile/utils/common_utils.dart';
import 'package:taonile/utils/double_utils.dart';
import 'package:taonile/utils/singleton_manager.dart';
import 'package:taonile/views/default_views.dart';

import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/event_msg.dart';
import '../utils/user_utils.dart';
import '../views/number_controller_widget.dart';

///
/// 购物车
///
class ShoppingCarPage extends StatefulWidget {
  const ShoppingCarPage({Key? key}) : super(key: key);

  @override
  State<ShoppingCarPage> createState() => _ShoppingCarPageState();
}

class _ShoppingCarPageState extends State<ShoppingCarPage> {
  List<ShoppingCarListData> datas = [];
  bool isAllCheck = false;
  var subTitle = '编辑';
  var amount = '0.00';
  var checkIds = '';
  double expressAmount = 0;

  @override
  void initState() {
    super.initState();
    getDatas();
    SingletonManager.instance.eventBus.on<ShoppingCarUp>().listen((event) {
      print('刷新一下下购物车');
      getDatas();
    });
  }

  getDatas() async {
    if (await UserUtils.isLogin() == false) {
      return;
    }

    dynamic result = await Api.shoppingCarList();
    ShoppingCarListEntity entity = ShoppingCarListEntity.fromJson(result);
    setState(() {
      datas.clear();
      if (entity.data.isNotEmpty) {
        datas.addAll(entity.data);
      }
    });
  }

  upNumCar(String carId, String up) async {
    dynamic result = await Api.upShoppingCar({
      'cart_id': carId,
      'upORdown': up,
    });
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("修改成功");
    }
  }

  deleteCar() async {
    dynamic result = await Api.deleteShoppingCar(checkIds);
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("删除成功");
      getDatas();
    }
  }

  getSkuStr(List<ShoppingCarListDataGoodsDataSkuData> currentSku) {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < currentSku.length; i++) {
      sb.write(currentSku[i].skuVal);
      if (i != currentSku.length - 1) {
        sb.write('/');
      }
    }
    return sb.toString();
  }

  //点击店铺的checkbox
  checkMall(bool isCheck, int index) {
    for (var item in datas[index].goodsData) {
      item.isCheck = isCheck;
    }
    isAllCheck = isAll();
  }

  //点击了全选
  checkAll(bool isCheck) {
    for (var item in datas) {
      item.isCheck = isCheck;
      for (var item2 in item.goodsData) {
        item2.isCheck = isCheck;
      }
    }
    isAllCheck = isAll();
  }

  //判断是否全部选中了
  isAll() {
    for (var item in datas) {
      if (item.isCheck == false) {
        return false;
      }
      for (var item2 in item.goodsData) {
        if (item2.isCheck == false) {
          return false;
        }
      }
    }
    return true;
  }

  //判断某店铺是否全部取消了
  isMallAll(int index) {
    bool isMall = true;
    for (var item in datas[index].goodsData) {
      if (item.isCheck == true) {
        isMall = false;
      }
    }
    return isMall;
  }

  //计算所有已选中的商品价格合计
  getCheckAmount() {
    double amount = 0;
    expressAmount = 0;
    StringBuffer ids = StringBuffer();
    for (var item in datas) {
      if (item.isCheck) {
        expressAmount += double.parse(item.storeExpressMoney);
      }
      for (var item2 in item.goodsData) {
        if (item2.isCheck) {
          amount += double.parse(item2.price) * double.parse(item2.num);
          ids.write(item2.businessCartId);
          ids.write(',');
        }
      }
    }
    if (ids.length > 1) {
      checkIds = ids.toString().substring(0, ids.length - 1);
    }
    return '${DoubleUtils.formartNum(amount + expressAmount, 2)}金券(运费$expressAmount)';
  }

  gotoConfirm() {
    List<ShoppingCarListData> result = [];
    for (var item in datas) {
      if (item.isCheck) {
        ShoppingCarListData mall = ShoppingCarListData();
        mall.isCheck = item.isCheck;
        mall.storeId = item.storeId;
        mall.storeBaseName = item.storeBaseName;
        mall.storeLogo = item.storeLogo;
        mall.goodsData = [];
        for (var item2 in item.goodsData) {
          if (item2.isCheck) {
            mall.goodsData.add(item2);
          }
        }
        result.add(mall);
      }
    }
    if (result.isNotEmpty) {
      SingletonManager.instance.currentCarConfirm = result;
      Routes.navigateTo(context, Routes.orderConfirm, params: {
        'tag': '2',
        'isCar': '1',
        'amount': amount,
        'expressMoney': expressAmount.toString(),
      }).then((value) {});
    }
  }

  getListItem(int index) {
    return InkWell(
      onTap: () {
        // Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.only(top: 20.w, left: 25.w, right: 25.w, bottom: 10.w),
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(20.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  RoundCheckBox(
                      size: 18,
                      checkedWidget: const Icon(
                        Icons.check,
                        color: Colors.white,
                        size: 10,
                      ),
                      checkedColor: Config.colorMain,
                      uncheckedColor: Config.colorBg,
                      border: Border.all(
                          color: datas[index].isCheck ? Config.colorMain : Config.colorText3,
                          width: 1),
                      isChecked: datas[index].isCheck,
                      onTap: (selected) {
                        setState(() {
                          datas[index].isCheck = !datas[index].isCheck;
                          checkMall(datas[index].isCheck, index);
                          amount = getCheckAmount();
                        });
                      }),
                  Padding(
                    padding: EdgeInsets.only(left: 20.w),
                  ),
                  Text(
                    datas[index].storeBaseName,
                    style: TextStyle(fontSize: 26.sp),
                  ),
                ],
              ),
            ),
            Divider(
              height: 5.w,
              thickness: 2.w,
              color: Config.colorDivider,
            ),
            ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 0.w),
              itemCount: datas[index].goodsData.length,
              shrinkWrap: true,
              scrollDirection: Axis.vertical,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (BuildContext context, int index2) {
                return getListItem2(index, index2);
              },
            ),
          ],
        ),
      ),
    );
  }

  getListItem2(int index, int index2) {
    return InkWell(
        onTap: () {
          if (subTitle == '编辑') {
            Routes.navigateTo(context, Routes.productDetail,
                params: {'productId': datas[index].goodsData[index2].goodsId});
          }
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
          height: 158.w,
          width: double.infinity,
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(color: Config.colorDivider, width: 1.w)),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              RoundCheckBox(
                  size: 18,
                  checkedWidget: const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 10,
                  ),
                  checkedColor: Config.colorMain,
                  uncheckedColor: Config.colorBg,
                  border: Border.all(
                      color: datas[index].goodsData[index2].isCheck
                          ? Config.colorMain
                          : Config.colorText3,
                      width: 1),
                  isChecked: datas[index].goodsData[index2].isCheck,
                  onTap: (selected) {
                    setState(() {
                      datas[index].goodsData[index2].isCheck =
                          !datas[index].goodsData[index2].isCheck;
                      if (selected == true) {
                        datas[index].isCheck = true;
                      } else {
                        datas[index].isCheck = !isMallAll(index);
                      }
                      amount = getCheckAmount();
                    });
                  }),
              Padding(
                padding: EdgeInsets.only(left: 20.w),
              ),
              Container(
                margin: EdgeInsets.only(right: 20.w),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: CachedNetworkImage(
                    imageUrl: CommonUtils.compressImageUrl(
                        datas[index].goodsData[index2].imgPath, 200, 200),
                    fit: BoxFit.fill,
                    width: 100.w,
                    height: 100.w,
                    errorWidget: (context, url, error) {
                      return Image.asset(
                        'assets/images/bg_default_400.png',
                        width: 100.w,
                        height: 100.w,
                        fit: BoxFit.fill,
                      );
                    },
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 470.w,
                    child: Text(
                      datas[index].goodsData[index2].shopGoodsName,
                      softWrap: false,
                      style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                    ),
                  ),
                  Container(
                    width: 470.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          getSkuStr(datas[index].goodsData[index2].skuData),
                          softWrap: true,
                          style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                        ),
                        Visibility(
                          visible: subTitle == '编辑',
                          child: Text(
                            "X${datas[index].goodsData[index2].num}",
                            softWrap: true,
                            style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 9.w),
                  ),
                  Container(
                    height: 45.w,
                    width: 470.w,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '${datas[index].goodsData[index2].price}金券',
                          softWrap: true,
                          style: TextStyle(color: Colors.red, fontSize: 22.w),
                        ),
                        Visibility(
                            visible: subTitle == '完成',
                            child: NumberControllerWidget(
                              height: 45.w,
                              width: 80.w,
                              numText: datas[index].goodsData[index2].num,
                              addValueChanged: (num) {
                                setState(() {
                                  datas[index].goodsData[index2].num = num.toString();
                                  print('+++++++++');
                                  upNumCar(datas[index].goodsData[index2].businessCartId, '1');
                                });
                              },
                              removeValueChanged: (num) {
                                setState(() {
                                  datas[index].goodsData[index2].num = num.toString();
                                  print('----------');
                                  upNumCar(datas[index].goodsData[index2].businessCartId, '0');
                                });
                              },
                              updateValueChanged: (num) {},
                            )),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: Text("购物车"),
        centerTitle: true,
        actions: [
          TextButton(
            child: Text(
              subTitle,
              style: TextStyle(color: Config.colorText1, fontSize: 26.w),
            ),
            onPressed: () {
              setState(() {
                if (subTitle == '编辑') {
                  if (datas.isEmpty) {
                    return;
                  }
                  subTitle = '完成';
                } else {
                  subTitle = '编辑';
                  amount = getCheckAmount();
                }
              });
            },
          ),
        ],
      ),
      bottomNavigationBar: Container(
        decoration: const BoxDecoration(color: Config.colorBg),
        height: 100.w,
        width: 750.w,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                RoundCheckBox(
                    size: 18,
                    checkedWidget: const Icon(
                      Icons.check,
                      color: Colors.white,
                      size: 10,
                    ),
                    checkedColor: Config.colorMain,
                    uncheckedColor: Config.colorBg,
                    border: Border.all(
                        color: isAllCheck ? Config.colorMain : Config.colorText3, width: 1),
                    isChecked: isAllCheck,
                    onTap: (selected) {
                      isAllCheck = !isAllCheck;
                      setState(() {
                        checkAll(isAllCheck);
                        amount = getCheckAmount();
                      });
                    }),
                Padding(
                  padding: EdgeInsets.only(left: 20.w),
                ),
                Text(
                  '全选',
                  style: TextStyle(fontSize: 26.sp),
                ),
              ],
            ),
            Stack(
              children: [
                Visibility(
                  visible: subTitle == '编辑',
                  child: Row(
                    children: [
                      SizedBox(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('合计:',
                                style: TextStyle(fontSize: 24.sp, color: Config.colorText1)),
                            Text(amount,
                                style: TextStyle(fontSize: 24.sp, color: Colors.redAccent)),
                          ],
                        ),
                      ),
                      Container(
                        width: 200.w,
                        margin: EdgeInsets.only(left: 20.w),
                        child: ElevatedButton(
                          clipBehavior: Clip.antiAlias,
                          onPressed: () {
                            gotoConfirm();
                          },
                          style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                          child: const Text('结算'),
                        ),
                      ),
                    ],
                  ),
                ),
                Visibility(
                  visible: subTitle == '完成',
                  child: Row(
                    children: [
                      Container(
                        width: 200.w,
                        margin: EdgeInsets.only(left: 25.w),
                        child: ElevatedButton(
                          clipBehavior: Clip.antiAlias,
                          onPressed: () {
                            deleteCar();
                          },
                          style: ElevatedButton.styleFrom(
                              primary: Colors.orange, shape: const StadiumBorder()),
                          child: const Text('删除'),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      body: datas.isNotEmpty
          ? Container(
              width: double.infinity,
              height: double.infinity,
              child: ListView.builder(
                padding: EdgeInsets.symmetric(horizontal: 0.w),
                itemCount: datas.length,
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                physics: const BouncingScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  return getListItem(index);
                },
              ),
            )
          : showNullData(tip: '购物车空空如也'),
    );
  }
}
